package com.smartum.mpr.server;

import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 */
public class FileUploadServlet extends HttpServlet {
    private static final List<String> acceptableFormats = new ArrayList<String>(Arrays.asList("image/gif",
            "image/jpeg", "image/pjpeg", "image/png", "image/vnd.wap.wbmp"));

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        final String realPath = getServletContext().getRealPath("/");
        final Date date = new Date();
        final String SAVE_PATH = "resources/images/";
        String fileName = "no-photobig.gif";

        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            try {

                List items = upload.parseRequest(req);
                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    DiskFileItem item = (DiskFileItem) iter.next();
                    String contentType = item.getContentType();
                    if (acceptableFormats.contains(contentType)) {
                        fileName = item.getName();
                        File uploadedFile = new File(realPath + "images" + File.separator + date.getTime() + "_" + fileName);
                        item.write(uploadedFile);

                        fileName = date.getTime() + "_" + fileName;
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            PrintWriter out = resp.getWriter();
            resp.setContentType("text/html");
            out.println("<html><head><script type=\"text/javascript\">");
            out.println("function foo(){window.top.uploadComplete('" + fileName + "');}</script></head>");
            out.println("<body onload=\"foo();\">");
            out.println("</body></html>");
        }
    }
}
